Dough Git

clove/pkviewer

web/src/routes/auth/[...segments]/+server.ts

back to web/src/routes/auth/[...segments]

/* web/src/routes/auth/[...segments]/+server.ts */
import type { RequestHandler } from "./$types";
import { site } from "$lib/config.ts";
import { apiOrigin } from "$lib/server/api.ts";

/**
 * Proxies the Discord OAuth endpoints to the API.
 *
 * The handshake is a browser redirect flow, so the browser must reach Discord
 * and receive the cookies the API sets. Only the auth endpoints are reachable,
 * so this cannot become a general proxy to the API.
 */
const ALLOWED = new Set([
  "discord/start",
  "discord/callback",
  "logout",
  "logout-all",
  "me",
]);

async function proxy(request: Request, url: URL, path: string, method: "GET" | "POST") {
  if (!ALLOWED.has(path)) {
    return new Response("Not found", { status: 404 });
  }

  let upstream: Response;
  try {
    upstream = await fetch(`${apiOrigin()}/auth/${path}${url.search}`, {
      method,
      headers: {
        cookie: request.headers.get("cookie") ?? "",
        // The API rejects state-changing requests without a recognised Origin
        origin: site.publicOrigin,
        accept: "application/json",
      },
      // The API's redirect goes to Discord and must reach the browser
      redirect: "manual",
    });
  } catch {
    // Not Response.redirect(): its headers are immutable, and the security hook must set them
    return new Response(null, {
      status: 302,
      headers: {
        location: `${site.publicOrigin}/login?error=unavailable`,
      },
    });
  }

  const headers = new Headers();

  // Every Set-Cookie must survive: they are the whole point of this proxy
  for (const cookie of upstream.headers.getSetCookie()) {
    headers.append("set-cookie", cookie);
  }

  const location = upstream.headers.get("location");
  if (location) {
    headers.set("location", location);
    return new Response(null, { status: upstream.status, headers });
  }

  const contentType = upstream.headers.get("content-type");
  if (contentType) headers.set("content-type", contentType);
  headers.set("cache-control", "no-store");

  return new Response(await upstream.text(), { status: upstream.status, headers });
}

export const GET: RequestHandler = ({ request, url, params }) =>
  proxy(request, url, params.segments, "GET");

export const POST: RequestHandler = ({ request, url, params }) =>
  proxy(request, url, params.segments, "POST");